//
//  LDAudioResumePlayer.swift
//  DingDongZP
//
//  Created by LeMac on 16/12/31.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

#import "LDAudioPlayer.h"
@import AVFoundation;
@interface LDAudioPlayer ()
{
    BOOL _isPrepare;//播放是否准备成功
    BOOL _isPlaying;//播放器是否正在播放
}

@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)NSTimer *timer;

@end
@implementation LDAudioPlayer

+(LDAudioPlayer*)sharePlayer {
    
    static LDAudioPlayer *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[self alloc] init];
    });
    return  player;
}

//-(void)setTimer:(NSTimer *)timer {
//
//}

- (instancetype)init {
    self = [super init];
    if (self) {
        
        //通知中心
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
//        self.player.pause;
        
//        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:AVPlayerItemDidPlayToEndTimeNotification object:nil] subscribeNext:^(id x) {
//            
//            if (x) {
//                
//                if (weakSelf.delegate) {
//                    [weakSelf.delegate playEnd:weakSelf];
//                }
//                
//                if (weakSelf.playEnd) {
//                    weakSelf.playEnd(weakSelf);
//                }
//            }
//        }];
    }
    return self;
}


-(AVPlayer*)player {
    
    if (_player == nil) {
        
        _player = [[AVPlayer alloc] init];
    }
    return _player;
}

-(BOOL)isPlaying {
    return _isPlaying;
    
}


-(void)setPrepareMusicUrl:(NSString*)urlStr {
    
    [self.player pause];
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:urlStr]];
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
    
    if (self.playNew) {
        self.playNew(self);
    }
    
    [self.player replaceCurrentItemWithPlayerItem:item];
}

-(void)play {
    
    if (!_isPrepare) {
        return;
    }
    [self.player play];
    _isPlaying = YES;
    
    //timer初始化
    if (_timer) { return; }
    
//    _timer = nil;
    //创建timer
    WEAKSELF
//    self.timer = [NSTimer bk_timerWithTimeInterval:0.5 block:^(NSTimer *timer) {
//        
//        [weakSelf updatePlayStatus];
//        
//    } repeats:true];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 block:^(NSTimer * _Nonnull timer) {
        
        [weakSelf updatePlayStatus];
    } repeats:true];
    
    
}
-(void)pause {
    if (!_isPlaying) {
        return;
    }
    
    if (self.playEnd) {
        
        self.playEnd(self);
    }
    
    [self.player pause];
    _isPlaying = NO;
    
    //销毁计时器
    [_timer invalidate];
    _timer = nil;
    
}

-(void)seekToTime:(float)time {
    
    //当音乐播放器时间改变时,先暂停后播放
    [self pause];
    [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            [self play];
        }
    }];
    
}

-(void)updatePlayStatus {
    
    
    //获取当前播放歌曲的时间
    float progress = 1.0 * self.player.currentTime.value / self.player.currentTime.timescale;
//    if (self.delegate&&[self.delegate respondsToSelector:@selector(playProgress:Progress:)]) {
//        
//        
//        [self.delegate playProgress:self Progress:progress];
//        
//    }
    if (self.playProgress) {
        self.playProgress(self,progress);
    }
    
}

-(void)playFinished:(NSNotification *)noti {
    
//    if (self.delegate && [self.delegate respondsToSelector:@selector(playProgress:Progress:)]) {
//        [self.delegate playEnd:self];
//    }
    
    if (self.playEnd) {
        self.playEnd(self);
    }
    
    [self pause];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    AVPlayerStatus staute = [change[@"new"] integerValue];
    switch (staute) {
        case AVPlayerStatusReadyToPlay:
            DDLog(@"音频加载成功");
            _isPrepare = YES;
            [self play];
            break;
//        case AVPlayerStatusFailed:
//            DDLog(@"加载失败");
//            
//            
//            break;
//        case AVPlayerStatusUnknown:
//            DDLog(@"资源找不到");
//            break;
            
            
        default:
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(playError:)]) {
                [self.delegate playError:self];
            }
            
            break;
    }
    
    DDLog(@"change:%@",change);
}



@end
